<?php
namespace api\wxapp\controller;
use wxapp\aes\Wxpay;
use think\Db;

class PayNoticeController{
    //微信支付回调
	public function notice(){
		// 微信公众平台推送过来的post数据
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		// 获取数据
		$data = Wxpay::FromXml($xml);
		
		// 保存微信服务器返回的签名sign
		$data_sign = $data['sign'];
		// sign不参与签名算法
		unset($data['sign']);
		
		$sign = $this->makeSign($data);
		
		// 判断签名是否正确  判断支付状态
		if ( ($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') ) {
			$result = $data;
			//获取服务器返回的数据
			$order_num = $data['out_trade_no'];         //订单单号			
			$transaction_id = $data['transaction_id'];  //微信支付流水号
			
			$online_transaction_no = array(
				'source' =>  'wxapp',     //支付来源
				'transaction_id'    =>  $transaction_id				
			);
			$status = Db::name('order')
			->where(['order_no'=>$order_num,'pay_status'=>0])
			->update(['online_transaction_no'=>json_encode($online_transaction_no),'pay_status'=>1,'pay_time'=>$data['time_end']]);
			if($status){
				$course_id = Db::name('order')
				->where('order_no','=',$order_num)
				->value('course_id');

				Db::name('school_course')
				->where('id','=',$course_id)
				->setInc('order_count',1);
			}	
		}else{
			$result = false;
		}		
		return $result;
	}

	/**
	 * 生成签名
	 * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
	 */
	public function MakeSign($data)
	{
        error_reporting(0);
		//签名步骤一：按字典序排序参数
		ksort($data);
		$string = $this->ToUrlParams($data);		
		//签名步骤二：在string后加入KEY
		
		$string = $string . "&key=2a336dc09120317722a8366b35051884";
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
	}

	/**
	 * 格式化参数格式化成url参数
	 */
	public function ToUrlParams($data)
	{
		$buff = "";
		foreach ($data as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}
}